<template>
    <el-container class="video">
        <el-page-header @back="goBack" :content="`${title} - 视频`">
        </el-page-header>
        <div class="video-header">
            <el-button size="small" type="primary" @click="openDialog('add')">添加视频</el-button>
        </div>

        <el-main class="video__content">
            <div ref="container" class="table-container">
                <el-table ref="table" :data="datas" style="width: 100%" align="center" header-align="center">
                    <el-table-column label="视频标题" prop="title" center />

                    <el-table-column label="时长" center width="120">

                        <template slot-scope="scope">
                            {{ formatSecond(scope.row.duration) }}
                        </template>

                    </el-table-column>


                    <el-table-column label="视频封面" center width="120px">

                        <template slot-scope="scope">
                            <template v-if="scope.row.poster">
                                <el-image :src="scope.row.poster" style="width: 120px" fit="cover" />
                            </template>
                            <template v-else>
                                <el-button size="small" type="text">后台正在生成中...</el-button>
                            </template>
                        </template>

                    </el-table-column>

                
                    <el-table-column label="视频收费类型">
                        <template slot-scope="scope">
                            &nbsp;&nbsp;&nbsp;&nbsp;{{ scope.row.type === 0 ? "免费" : "收费" }}
                        </template>
                    </el-table-column>



                    <el-table-column label="上传时间" center>
                        <template slot-scope="scope">
                            {{ $dayjs(scope.row.createdAt).format('YYYY-MM-DD HH:mm') }}
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" center width="400px">
                        <template slot-scope="scope">
                            <el-button type="primary" size="small" @click="openDialog('edit', scope.row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>

                            <el-button size="small" @click="downloadvideo(scope.row.originalVideoLink)">下载</el-button>
                            <template v-if="scope.row.transcodingStatus === 0">
                                <el-button type="success" size="small" v-if="!scope.row.streamingVideoLink"
                                    @click="updateStreaming(scope.row)">转码</el-button>
                            </template>

                            <template v-else-if="scope.row.transcodingStatus === 1">
                                <el-button type="success" size="small" :loading="true">转码中...</el-button>
                            </template>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-main>

        <el-dialog :title="dialogText" :visible.sync="dialogVisible" width="50%" center :lock-scroll="true" top="40px"
            :close-on-press-escape="false" :close-on-click-modal="false" v-if="dialogVisible">
            <el-form label-width="160px">
                <el-form-item label="标题" :required="true">
                    <el-input v-model="formData.title" placeholder="请输入视频标题" />
                </el-form-item>
                <el-form-item label="收费类型" :required="true">
                    <el-select v-model="formData.type" placeholder="请选择收费类型">
                        <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="视频" :required="true">
                    <upload-video ref="uploadVideo" :url.sync="formData.originalVideoLink" />
                </el-form-item>



            </el-form>
            <span slot="footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="handleCreate">保存视频</el-button>
            </span>
        </el-dialog>
    </el-container>
</template>

<script>


export default {
    name: "videoList",

    data() {
        return {
            datas: [],
            dialogVisible: false,
            dialogVisibleType: "add",
            typeList: [
                {
                    value: 0,
                    label: "免费",
                },
                {
                    value: 1,
                    label: "收费",
                },
            ],
            formData: {
                title: "",
                type: 0,
                originalVideoLink: null,
            },
            intervalMap: {}
        };
    },

    computed: {
        dialogText() {
            if (this.dialogVisibleType === "edit") {
                return "编辑视频";

            }
            return "添加视频";
        },

        title() {
            const { title } = this.$route.query;
            return title;
        },
    },

    created() {
        this.handleDatas();
    },
    beforeDestroy() {
        Object.value(this.intervalMap).forEach((item) => {
            clearInterval(item)
        })
    },
    methods: {
        downloadvideo(link) {
            window.open(link, "_blank");
        },
        async handleDatas() {
            const loading = this.$loading();
            try {
                const { lessonId } = this.$route.query;
                const { data } = await this.$fetch.get("/api/topic-lesson-video/list", {
                    lessonId,
                });
                this.datas = data;
            } catch (error) {
                console.log(error);
            }
            loading.close();
        },
        refresh() {
            this.handleDatas();
        },

        async openDialog(type = "add", row = {}) {
            this.dialogVisibleType = type;
            if (type === "add") {
                this.formData = {
                    title: "",
                    type: 0,
                    originalVideoLink: null,
                }
            } else {
                const { data } = await this.$fetch.get('/api/topic-lesson-video/get', {
                    id: row.id
                })
                console.log("data", data)
                this.formData = {
                    ...this.formData,
                    ...data
                }
            }

            this.dialogVisible = true;

        },

        cancel() {
            this.dialogVisible = false;
            this.refresh();
        },

        handleDelete(row) {
            const params = {
                id: row.id,
            };
            this.$confirm("确定要删除此视频？", "", {
                distinguishCancelAndClose: true,
                confirmButtonText: "确认",
                cancelButtonText: "取消",
            }).then(async () => {
                const { code } = await this.$fetch.post(
                    "/api/topic-lesson-video/delete",
                    params
                );
                if (code === 0) {
                    this.$message.success("删除成功");
                }
                this.refresh();
            });
        },

        async handleCreate() {


            const { title, originalVideoLink } = this.formData

            const rules = [
                {
                    case: !title,
                    message: "请输入视频标题",
                },
                {
                    case: !originalVideoLink,
                    message: "请上传视频",
                },
            ]

            const valid = this.$validForm(rules)


            if (!valid) {
                return
            }


            const url = this.dialogVisibleType === "add" ? "/api/topic-lesson-video/create" : "/api/topic-lesson-video/update";
            const { topicId, lessonId } = this.$route.query;

            const res = await this.$fetch.post(url, {
                ...this.formData,
                topicId: Number(topicId),
                lessonId: Number(lessonId),
            });

            if (res.code === 0) {
                this.$message.success(this.dialogVisibleType === "add" ? "添加成功" : "修改成功");
            }

            this.cancel();
        },


        async uploadFile(file) {
            try {
                console.log(file);
                const data = await this.$fetch.cosUplod(file, "/assets/topic-lesson-videos/origin");
                if (data) {
                    this.formData.originalVideoLink = data;
                } else {
                    throw new Error("视频上传失败");
                }
            } catch (error) {
                this.$message.error("视频上传出错，请重试！");
            }
        },

        async updateStreaming(row) {
            const id = row.id;

            this.$fetch.post("/api/topic-lesson-video/updateStreaming", {
                id,
            });

            this.$set(row, 'transcodingStatus', 1)

            this.pollingVideoStatus(row)
        },

        pollingVideoStatus(row) {
            const id = row.id;
            if (this.intervalMap[id]) {
                clearInterval(this.intervalMap[id])
            }
            const interval = setInterval(async () => {
                const { code, data: { transcodingStatus } = {} } = await this.$fetch.get("/api/topic-lesson-video/get", {
                    id,
                });
                this.$set(row, 'transcodingStatus', transcodingStatus)
                if (code === 0 && transcodingStatus === 2) {
                    clearInterval(this.intervalMap[id]);
                    this.refresh();
                    this.$message.success("视频转码成功");
                }
            }, 5000);
            this.intervalMap[id] = interval;
        },

        async deleteLink() {
            const { code } = await this.$fetch.post("/api/cos-delete", {
                url: this.formData.link,
            });
            if (code === 0) {
                this.formData.link = "";
            }
        },
        goBack() {
            this.$router.go(-1);
        },

        formatSecond(seconds) {
            if (!seconds) {
                return ''
            }
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const remainingSeconds = Math.floor(seconds % 60);
            const formattedHours = String(hours).padStart(2, '0');
            const formattedMinutes = String(minutes).padStart(2, '0');
            const formattedSeconds = String(remainingSeconds).padStart(2, '0');
            return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
        }
    },
};
</script>

<style scoped lang="scss">
.video {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 50px);

    .title {
        font-size: 26px;
        width: 100%;
        line-height: 42px;
        justify-content: center;
        align-items: center;
        display: flex;
    }

    .video-header {
        height: 40px;
        display: flex;
        align-items: center;
        margin-top: 30px;
    }

    .video__content {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: auto;
        padding-bottom: 0;

        .table-container {
            flex: 1;
            overflow: hidden;
            overflow-y: auto;
        }
    }

    .pagination-container {
        display: flex;
        justify-content: center;
        padding: 20px 0;

        .el-pagination {
            padding: 20px 0;
        }
    }
}
</style>
